import java.util.ArrayList;
import java.util.List;

public class Solution1302 {

    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public int deepestLeavesSum(TreeNode root) {
        List<Integer> list=new ArrayList<>();
        dfs(root,list,0);
        return list.get(list.size()-1);
    }

    private void dfs(TreeNode root, List<Integer> list, int k) {
        if (root==null){
            return;
        }
        if (k==list.size()){
            list.add(0);
        }
        list.set(k,list.get(k)+root.val);
        dfs(root.left,list,k+1);
        dfs(root.right,list,k+1);
    }

    public static void main(String[] args) {
        System.out.println(new Solution1302().deepestLeavesSum(new TreeNode(1,new TreeNode(2,new TreeNode(4,new TreeNode(7),null),new TreeNode(5)),new TreeNode(3,null,new TreeNode(6,null,new TreeNode(8))))));
    }
}
